/**
 * 
 */
package v1c08;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

/**
 * @author gjunming@gmail.com
 * @version Aug 7, 2009 3:26:17 PM
 */
public class ActionTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			private static final int FWIDTH = 300;
			private static final int FHEIGHT = 200;

			@Override
			public void run() {
				ActionFrame actionFrame = new ActionFrame();
				actionFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				actionFrame.setVisible(true);
				actionFrame.setSize(FWIDTH, FHEIGHT);
			}
		});
	}

}

class ActionFrame extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final JPanel actionPanel;

	public ActionFrame() {
		actionPanel = new JPanel();

		// create action and bind input map with name to action map
		Action yellowAction = new ColorAction("Yellow", Color.YELLOW);
		Action blueAction = new ColorAction("Blue", Color.BLUE);
		Action redAction = new ColorAction("Red", Color.RED);

		// create button
		actionPanel.add(new JButton(yellowAction));
		actionPanel.add(new JButton(blueAction));
		actionPanel.add(new JButton(redAction));

		add(actionPanel);

		InputMap imap = actionPanel
				.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
		imap.put(KeyStroke.getKeyStroke("ctrl Y"), "my.yellow");// Y must be
																// captical
		imap.put(KeyStroke.getKeyStroke("ctrl B"), "my.blue");
		imap.put(KeyStroke.getKeyStroke("ctrl R"), "my.red");

		ActionMap amap = actionPanel.getActionMap();
		amap.put("my.yellow", yellowAction);
		amap.put("my.blue", blueAction);
		amap.put("my.red", redAction);

	}

	class ColorAction extends AbstractAction {

		private static final long serialVersionUID = 1L;

		/*
		 * @see
		 * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent
		 * )
		 */
		public ColorAction(String name, Color c) {
			putValue(Action.NAME, name);
			// putValue(Action.SMALL_ICON, icon);
			putValue(Action.SHORT_DESCRIPTION,
					"Click me, And it will call color" + name.toLowerCase());
			putValue("color", c);
		}

		@Override
		public void actionPerformed(ActionEvent event) {
			Color bg = (Color) getValue("color");
			actionPanel.setBackground(bg);
		}
	}
}